<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <!-- 开 1 关 0 -->
            <el-switch v-if="row.isEdit" v-model="row.state" :active-value="1" :inactive-value="0" />
            <span v-else>  {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="submitEditForm(row)">确定</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="onShowAssign(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" size="mini" type="text" style="margin-left:10px">删除</el-button>
              </el-popconfirm>
              <!-- <el-button slot="reference" size="mini" type="text">删除</el-button> -->
            </template>
          </template>
        </el-table-column>

      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form ref="addRoleRorm" label-width="120px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" active-value="1" inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="submitForm">确定</el-button>
              <el-button size="mini">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 2. 使用dialog组件弹出内容 -->
    <el-dialog title="分配角色" :visible.sync="showAssign">
      <el-tree
        ref="permTree"
        :default-checked-keys="permIds"
        node-key="id"
        :data="roleList"
        :props="{label:'name'}"
        default-expand-all
        show-checkbox
        check-strictly
      />
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="onPermTree">确认</el-button>
          <el-button size="mini" @click="showAssign=false">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRoleList, updateRole, delRole, rolesdDetailsAPI, assignPremRolesAPI } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      permIds: [],
      roleList: [],
      showAssign: false,
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 1
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 模态框点过确定
    async onPermTree() {
      await assignPremRolesAPI(this.id, this.$refs.permTree.getCheckedKeys())
      // console.log(this.$refs.permTree.getCheckedKeys())
      this.$message.success('权限分配成功')
      this.showAssign = false
    },
    // 分配权限渲染模态框
    async onShowAssign(id) {
      this.id = id
      const { data } = await getPermissionList()
      this.roleList = transListToTreeData(data, 0)
      const res = await rolesdDetailsAPI(id)
      // console.log(res)-
      this.permIds = res.data.permIds
      this.showAssign = true
    },
    async getRoleList() {
      const res = await getRoleList({ page: this.pageParams.page, pagesize: this.pageParams.pagesize })
      this.list = res.data.rows.map(v => ({ ...v, isEdit: false, isEditRole: { name: v.name, description: v.description, state: v.state }})) // 赋值数据
      this.pageParams.total = res.data.total // 总条数赋值
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    async submitForm() {
      // 1 表单验证
      await this.$refs.addRoleRorm.validate()
      // 2 发送新增请求
      await addRoleList(this.roleForm)
      // 3 提示成功
      this.$message.success('新增成功')
      // 4 重置表单
      this.$refs.addRoleRorm.resetFields()
      // 5 关闭模态框
      this.showDialog = false
      // 6 刷新数据
      this.getRoleList()
    },
    btnEditRow(row) {
      // 开启编辑状态
      row.isEdit = true
    },
    cancelEdit(row) {
      // / 关闭启编辑状态
      row.isEdit = false
      row.name = row.isEditRole.name
      row.state = row.isEditRole.state
      row.description = row.isEditRole.description
    },
    async submitEditForm(row) {
      // // 表单的校验
      if (!row.name || !row.description) {
        this.$message.warning('角色和描述不能为空')
        return
      }
      await updateRole({ id: row.id, name: row.name, description: row.description, state: row.state })
      this.$message.success('角色编辑成功')
      // // 对象合并  给对象增加属性
      // Object.assign(row.isEditRole, { state: row.state, name: row.name, description: row.description })
      // Object.assign(row, { isEdit: false })
      // 这样可以省略重新调用接口渲染这一步，优化性能
      // this.getRoleList()
    },
    async confirmDel(id) {
      // const index = this.list.findIndex(v => v.id === id)
      await delRole(id)
      this.$message.success('删除成功')
      // 判断数组是不是最后一条 数据
      if (this.list.length === 1 && this.pageParams.page > 1) {
        // 当前页面 最后一条数据  =>
        this.pageParams.page--
      }
      this.getRoleList()
      // this.list.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
